import { IRpcSocketServer, RpcBridgeHost } from "rpc_dream"
import * as Net from "net"
import { TcpSocketRpcBridgeHost } from "./TcpSocketRpcBridgeHost";

export class RpcTcpSocketServer implements IRpcSocketServer<Net.Server> {
    onLaunch: () => void = null!
    onShutDown: () => void = () => {}
    onClientConnected: (client: RpcBridgeHost<any>) => void = null!
    onError: (error: Error) => void = error => {console.error(error)}
    public server: Net.Server = null!
    public constructor (private creator: () => Promise<Net.Server>, public bufferSize: number = 1024 * 128){

    }
    async prepareForLaunch(): Promise<void> {
        this.server = await this.creator()
        this.server.on("error", error => {
            this.onError(error)
        })
        this.server.on("close", () => {this.onShutDown()})
        this.server.on("connection", socket => {
            const host = new TcpSocketRpcBridgeHost(async () => socket, this.bufferSize)
            host.shouldBeCompleteInitializationByExternally = true
            this.onClientConnected(host)
        })
        this.server.on("listening", () => {
            this.onLaunch()
        })
    }
    shutdown(): Promise<void> {
        return new Promise<void>((resolve, reject) => {
            this.server.close(error => {
                if (error == null) resolve()
                else reject(error)
            })
        })
    }
}
